package com.evaluationSystem.util;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import com.evaluationSystem.enums.ContentTypeEnum;
import com.evaluationSystem.exception.EvaluationException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtil {
    public static void uploadExcel(MultipartFile multipartFile) {
        String fileName = multipartFile.getOriginalFilename();
        if (multipartFile.isEmpty()) {
            throw new EvaluationException("文件异常，请重试");
        }
        assert fileName != null;
        if (!fileName.endsWith("xls") && !fileName.endsWith("xlsx")) {
            throw new EvaluationException("文件格式错误,请重新选择 xlsx 或 xls 格式文件");
        }
    }

    public static void downTemplates(HttpServletResponse response, String fileName, String filePath) {
        try {
            if (StringUtils.isNotBlank(fileName)) {
                String suffix = fileName.substring(fileName.indexOf(".") + 1);
                response.setContentType(ContentTypeEnum.forEach_ContentTypeEnum(suffix).getValue());
            }
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, String.valueOf(StandardCharsets.UTF_8)));
//            response.setHeader("filename", URLEncoder.encode(fileName, String.valueOf(StandardCharsets.UTF_8)));
//            response.setHeader("Access-Control-Expose-Headers", "filename,Content-Disposition");

            //获取文件的路径，此方式本地开发可以运行，服务器无法获取文件
//            String filePath = getClass().getResource("/template/template.xlsx").getPath();
//            FileInputStream input = new FileInputStream(filePath);

            //在服务器中能够读取到模板文件
            ClassPathResource resource = new ClassPathResource(filePath);
            InputStream input = resource.getInputStream();
            OutputStream out = response.getOutputStream();
            byte[] b = new byte[2048];
            int len;
            while ((len = input.read(b)) != -1) {
                out.write(b, 0, len);
            }
            //修正 Excel在“xxx.xlsx”中发现不可读取的内容。是否恢复此工作薄的内容？如果信任此工作簿的来源，请点击"是"
//            response.setHeader("Content-Length", String.valueOf(input.getChannel().size()));
            input.close();
        } catch (Exception e) {
            throw new EvaluationException("下载失败");
        }
    }

    /**
     * 验证手机号是否合法
     */
    public static boolean isMobileNO(String mobile) {
        //大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
        String regex = "^((13[0-9])|(14[05679])|(15([0-3,5-9]))|(16[2567])|(17[01235678])|(18[0-9]|19[135689]))\\d{8}$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(mobile);
        return m.matches();
    }

    /**
     * 对列表进行分页
     **/
    public static <T> PageInfo<T> startPage(@NotNull List<T> list, Integer pageNum, Integer pageSize) {
        //创建Page类
        Page<T> page = new Page<>(pageNum, pageSize);
        //为Page类中的total属性赋值
        page.setTotal(list.size());
        //计算当前需要显示的数据下标起始值
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, list.size());
        //从链表中截取需要显示的子链表，并加入到Page
        page.addAll(list.subList(startIndex, endIndex));
        //以Page创建PageInfo
        return new PageInfo<>(page);
    }

}
